package com.qianji.petmall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qianji.common.to.seckill.SeckillSkuInfoTo;
import com.qianji.common.utils.DateTime;
import com.qianji.common.utils.PageUtils;
import com.qianji.common.utils.Query;
import com.qianji.common.utils.R;
import com.qianji.petmall.product.dao.SkuInfoDao;
import com.qianji.petmall.product.dao.SpuInfoDescDao;
import com.qianji.petmall.product.entity.SkuImagesEntity;
import com.qianji.petmall.product.entity.SkuInfoEntity;
import com.qianji.petmall.product.entity.SpuInfoDescEntity;
import com.qianji.petmall.product.feign.SeckillFeignService;
import com.qianji.petmall.product.service.AttrGroupService;
import com.qianji.petmall.product.service.SkuImagesService;
import com.qianji.petmall.product.service.SkuInfoService;
import com.qianji.petmall.product.service.SkuSaleAttrValueService;
import com.qianji.petmall.product.vo.SkuItemAttrVO;
import com.qianji.petmall.product.vo.SkuItemVo;
import com.qianji.petmall.product.vo.SpuItemAttrGroupVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    private SkuInfoDao skuInfoDao;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SpuInfoDescDao spuInfoDescDao;
    @Autowired
    private SkuSaleAttrValueService saleAttrValueService;
    @Autowired
    private AttrGroupService attrGroupService;
    @Autowired
    private ThreadPoolExecutor executor;
    @Autowired
    private SeckillFeignService seckillFeignService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.baseMapper.insert(skuInfoEntity);
    }

    @Override
    public PageUtils queryPageByQueryMoney(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> skuInfoEntityQueryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)){
            skuInfoEntityQueryWrapper.and(item->{
                item.eq("sku_id",key).or().like("sku_name",key);
            });
        }
        String catelogId = (String) params.get("catelogId");
        if (StringUtils.isNotEmpty(catelogId) && !"0".equals(catelogId)){
            skuInfoEntityQueryWrapper.eq("catalog_id",catelogId);
        }
        String brandId = (String) params.get("brandId");
        if (StringUtils.isNotEmpty(brandId) && !"0".equals(brandId)){
            skuInfoEntityQueryWrapper.eq("brand_id",brandId);
        }
        String min = (String) params.get("min");
        if (StringUtils.isNotEmpty(min)){
            skuInfoEntityQueryWrapper.ge("price",min);
        }
        String max = (String) params.get("max");
        if (StringUtils.isNotEmpty(max) && !max.equals("0")){
            skuInfoEntityQueryWrapper.le("price",max);
        }
        IPage<SkuInfoEntity> page = this.page(new Query<SkuInfoEntity>().getPage(params), skuInfoEntityQueryWrapper);
        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getSkuInfo(List<Long> skuId) {
        List<SkuInfoEntity> list = baseMapper.selectBatchIds(skuId);
        return list;
    }

    @Override
    public SkuItemVo item(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVo skuItemVo = new SkuItemVo();
//        //1、sku基本信息 pms_sku_info
//        SkuInfoEntity skuInfoEntity = skuInfoDao.selectById(skuId);
//        Long spuId = skuInfoEntity.getSpuId();
//        Long catalogId = skuInfoEntity.getCatalogId();
//        skuItemVo.setInfo(skuInfoEntity);
//        //2、sku图片信息 pms_sku_images
//        List<SkuImagesEntity> skuImagesEntities = skuImagesService.selectById(skuId);
//        skuItemVo.setImages(skuImagesEntities);
//        //3、获得spu销售属性组合
//        List<SkuItemAttrVO> skuSaleAttrValueEntity = saleAttrValueService.selectByAttrValue(spuId);
//        skuItemVo.setItemAttr(skuSaleAttrValueEntity);
//        //4、获得spu介绍
//        SpuInfoDescEntity spuInfoDescEntity = spuInfoDescDao.selectById(spuId);
//        skuItemVo.setDesc(spuInfoDescEntity);
//        //5、获得spu规格参数
//        List<SpuItemAttrGroupVo> spuItemAttrGroupVos = attrGroupService.selectAttrGroup(spuId,catalogId);
//        skuItemVo.setItemGroup(spuItemAttrGroupVos);

        /**
         * 使用异步的方式执行
         */
        CompletableFuture<SkuInfoEntity> future = CompletableFuture.supplyAsync(() -> {
            SkuInfoEntity skuInfoEntity = skuInfoDao.selectById(skuId);
            skuItemVo.setInfo(skuInfoEntity);
            return skuInfoEntity;
        }, executor);
        //依赖于skuInfo的结果
        CompletableFuture<Void> future1 = future.thenAcceptAsync((item) -> {
            List<SkuItemAttrVO> skuSaleAttrValueEntity = saleAttrValueService.selectByAttrValue(item.getSpuId());
            skuItemVo.setItemAttr(skuSaleAttrValueEntity);
        },executor);
        CompletableFuture<Void> future2 = future.thenAcceptAsync((item) -> {
            SpuInfoDescEntity spuInfoDescEntity = spuInfoDescDao.selectById(item.getSpuId());
            skuItemVo.setDesc(spuInfoDescEntity);
        },executor);
        CompletableFuture<Void> future3 = future.thenAcceptAsync((item) -> {
            List<SpuItemAttrGroupVo> spuItemAttrGroupVos = attrGroupService.selectAttrGroup(item.getSpuId(), item.getCatalogId());
            skuItemVo.setItemGroup(spuItemAttrGroupVos);
        },executor);
        //不依赖于其它线程的结果
        CompletableFuture<Void> future4 = CompletableFuture.runAsync(() -> {
            List<SkuImagesEntity> skuImagesEntities = skuImagesService.selectById(skuId);
            skuItemVo.setImages(skuImagesEntities);
        });
        //查询当前商品是否有秒杀活动信息
        CompletableFuture<Void> future5 = CompletableFuture.runAsync(() -> {
            R skuInfo = seckillFeignService.getSeckillSkuInfo(skuId);
            if (skuInfo.getCode()==0){
                SeckillSkuInfoTo data = skuInfo.getData(new TypeReference<SeckillSkuInfoTo>() {});
                skuItemVo.setSkuInfoTo(data);
                if (data!=null){
                    Date startTime = data.getStartTime();
                    Date endTime = data.getEndTime();
                    try {
                        String s1 = DateTime.formatDate(startTime);
                        String s = DateTime.formatDate(endTime);
                        skuItemVo.setStartTime(s1);
                        skuItemVo.setEndTime(s);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    long thisTime = System.currentTimeMillis();
                    if (thisTime>data.getEndTime().getTime()){
                        //说明秒杀活动过期了
                        skuItemVo.setSkuInfoTo(null);
                    }
                }
            }
        }, executor);

        //当所有线程都执行完成后执行
        CompletableFuture.allOf(future,future1,future2,future3,future4,future5).get();

        return skuItemVo;
    }

    @Override
    public List<SkuInfoEntity> getSkuBySpuId(Long spuId) {
        List<SkuInfoEntity> spu_id = this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        return spu_id;
    }

}